package org.miyuki4j.cfgtool;

import lombok.Getter;
import org.miyuki4j.cfgtool.exception.TypeParseException;

import java.util.*;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/24/星期四 10:53
 * @Version 1.0
 */
@Getter
public class TableHeader implements Iterable<TableField>, TypeParseable {

    private final List<TableField> fields = new ArrayList<>();
    private final int rowNum;
    private final int columnNum;

    private final Set<Integer> columnIndexes = new LinkedHashSet<>();

    public TableHeader(int rowNum, int columnNum) {
        this.rowNum = rowNum;
        this.columnNum = columnNum;
    }

    @Override
    public Iterator<TableField> iterator() {
        return fields.iterator();
    }

    public Optional<TableField> get(final int index) {
        return fields.stream().filter(field -> field.getIndex() == index).findFirst();
    }

    public Optional<TableField> get(final String name) {
        return fields.stream().filter(field -> Objects.equals(field.getName(), name)).findFirst();
    }

    public void add(final TableField field) {
        fields.add(field);
        columnIndexes.add(field.getIndex());
    }

    @Override
    public String toString() {
        return "TableHeader{" + "fields=" + fields + '}';
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        TableHeader that = (TableHeader) o;
        return Objects.equals(fields, that.fields);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(fields);
    }

    @Override
    public void parse() {
        for (TableField field : fields) {
            field.parse();
        }
        Optional<TableField> id = get("id");
        if (!id.isPresent()) {
            throw new TypeParseException("No id field found");
        }
    }

}
